//公共方法
var Vue = require('vue');
// Vue.http.options.credentials = true;

function post(url, param, dataForm = null, callBack, failBack = null) {
  let token = sessionStorage.getItem('token');
  let sendUrl = url;
  for (let item in dataForm) {
    sendUrl = sendUrl + "?" + item + '=' + dataForm[item];
  }
  Vue.default.http.post(sendUrl, param, {
    headers: {
      sessionId: token
    }
  }).then(res => {
    callBack(res.body)
  }, res => {
    if (failBack) {
      failBack(res.body)
    }
  });
}


function get(url, param, dataForm = null, callBack, failBack = null) {
  let token = sessionStorage.getItem('token');
  let sendUrl = url;
  for (let item in dataForm) {
    sendUrl = sendUrl + "?" + item + '=' + dataForm[item];
  }
  Vue.default.http.get(sendUrl, {
    headers: {
      'sessionId': token
    },
    emulateJSON: true,
    credentials: true
  }).then(res => {
    callBack(res.body)
  }, res => {
    if (failBack) {
      failBack(res.body)
    }
  })
  // Vue.default.http.get(sendUrl, param, {
  //   headers: {
  //     sessionId: token
  //   }
  // }).then(res => {
  //   callBack(res.body)
  // }, res => {
  //   if (failBack) {
  //     failBack(res.body)
  //   }
  // });
}

function formSubmit(url, param, callBack, failBack = null) {
  Vue.default.http.post(url, param, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    emulateJSON: true
  }).then(res => {
    callBack(res.data)
  }, res => {
    if (failBack) {
      failBack(res.data)
    }
  });
}

function uploadFile(url, param, contentType, callBack, failBack = null) { // 上传图片到阿里云
  Vue.default.http.put(url, param, {
    headers: {
      'Content-Type': contentType
    },
    emulateJSON: false
  }).then(res => {
    callBack(res.data)
  }, res => {
    if (failBack) {
      failBack(res.data)
    }
  });
}

function setCookie(name, value) {
  var Days = 2;
  var exp = new Date();
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  // document.cookie = name + "=" + escape(value) ;
  document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
}

//读取cookie：
function getCookie(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  return (arr = document.cookie.match(reg)) ? unescape(arr[2]) : null;
}

module.exports = {
  post: post,
  get: get,
  getCookie: getCookie,
  uploadFile: uploadFile,
  formSubmit: formSubmit
}
